package kt.com.bilin.coin.api

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.bilin.coin.ApiConstant
import com.bilin.coin.utils.GsonUtil
import com.bilin.coin.utils.SharedPreferencesUtils
import kt.com.bilin.coin.utils.Logger
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

/**
 * Created by zhoucl on 2019/11/12 0012.
 */
class SignInterceptor : Interceptor {

    companion object {
        const val PARAM = "PARAM"
        const val COOKIE = "Cookie"
        const val CSRF_TOKEN = "a_csrfToken"
        const val A_TOKEN = "a_token"
        const val DEVICE = "device"
    }

    @Throws(Exception::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val newBuilder = chain.request().newBuilder()
        val cookie = SharedPreferencesUtils.getInstance().getString("Cookie", "")
        val mapCookie = GsonUtil.GsonToMaps<Any>(cookie)
        val buffer = StringBuffer()
        if (mapCookie != null) {
            for (key in mapCookie.keys) {
                buffer.append(key).append("=").append(mapCookie[key]).append("; ")
            }
        }
        newBuilder.addHeader(COOKIE, "${buffer}lang=cn;Path=/")
        newBuilder.addHeader(CSRF_TOKEN, SharedPreferencesUtils.getInstance().getString(ApiConstant.CSRF_TOKEN, ""))
        newBuilder.addHeader(A_TOKEN, SharedPreferencesUtils.getInstance().getString(ApiConstant.RegisterToken, ""))
        newBuilder.addHeader(DEVICE, "android")
        val response = chain.proceed(newBuilder.build())
        val bodyString = response.body?.string()
        val defaultResult = JSONObject().apply {
            put("code", 200)
            put("msg", "操作成功")
        }
        var newBody = defaultResult
        kotlin.runCatching { newBody = JSON.parseObject(bodyString ?: defaultResult.toJSONString()) }
        val data = newBody["data"]
        if (data is String && data.isBlank()) {
            newBody["data"] = null
        }
        return response.newBuilder().body(newBody.toJSONString().toResponseBody("application/json".toMediaType())).build()
    }
}